<template>
  <div class="container">
    <div class="apply-container">
      <div class="apply-container-head"></div>
      <div class="apply-container-body">
        <div class="apply-container-body-title">
          <div class="apply-container-body-title-font">报账申请</div>
          <div class="apply-container-body-title-return">
            <el-button size="small" @click="goBackPage">返回</el-button>
          </div>
        </div>
        <el-divider class="apply-container-body-title-line"></el-divider>
        <div class="apply-container-body-content">
          <el-form :model="BillOrder" label-width="125px" ref="BillOrder" label-position="LabelPosition"
            :rules="BillOrderRules" style="width: 100%;">

            <el-form-item label="姓名:" prop="InputUserName" style="width: 40%;">
              <el-input v-model="BillOrder.InputUserName" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="工号:" prop="InputUserId" style="width: 40%;">
              <el-input v-model="BillOrder.InputUserId" placeholder="请输入工号" clearable></el-input>
            </el-form-item>
            <el-form-item label="申请人电话:" prop="InputUserPhone" style="width: 40%;">
              <el-input v-model="BillOrder.InputUserPhone" placeholder="请输入申请人电话" clearable></el-input>
            </el-form-item>
            <el-form-item label="报账车辆车牌号:" prop="SelectAutoPlateNum" style="width: 40%;">
              <el-select v-model="BillOrder.SelectAutoPlateNum" placeholder="请选择报账车辆车牌号" clearable>
                <el-option v-for="item in BillOrder.SelectAutoPlateNumOptions" :key="item" :label="item"
                  :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="报账类型:" prop="SelectBillType" style="width: 40%;">
              <el-select v-model="BillOrder.SelectBillType" placeholder="请选择报账类型" clearable>
                <el-option label="用车费" value="用车费"></el-option>
                <el-option label="维修费" value="维修费"></el-option>
                <el-option label="保险费" value="保险费"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="具体描述:" prop="InputBillDescribe" style="width: 50%;">
              <el-input v-model="BillOrder.InputBillDescribe" type="textarea" placeholder="请输入具体描述" maxlength="100"
                show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="费用合计:" prop="InputBillTotal" style="width: 40%;">
              <el-input v-model="BillOrder.InputBillTotal" placeholder="请输入费用合计" clearable></el-input>
            </el-form-item>
            <el-form-item label="价格清单表" prop="BillReceipt" style="width: 55%;">
              <el-upload v-model="BillOrder.BillReceipt" class="upload-demo " action="http://localhost:8088/upload"
                accept=".png, .jpg" :on-success="BillReceiptGetUrl" :on-preview="handlePreview" :on-remove="handleRemove"
                :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed">
                <el-button size="small" type="primary">点击上传</el-button>
                <span slot="tip" class="el-upload__tip width">（只能上传png/jpg文件，且不超过10M）</span>
              </el-upload>
            </el-form-item>
            <div class="apply-container-body-content-submit">
              <el-button type="primary" @click="CreateBill('BillOrder')">提交</el-button>
            </div>
          </el-form>
        </div>
      </div>
      <div class="apply-container-footer"></div>
    </div>
  </div>
</template>
  
<script>
import { fetchPlateNums } from '@/api/archives.js'
import { createBill } from '@/api/bill'
import { getUserInfoById } from '@/api/user.js';
export default {
  name: 'BillApplicationView',
  data() {
    return {
      LabelPosition: 'right',
      BillOrder: {
        InputUserName: null,
        InputUserId: null,
        InputUserPhone: null,
        SelectAutoPlateNum: null,
        SelectAutoPlateNumOptions: [],
        SelectBillType: null,
        InputBillDescribe: null,
        InputBillTotal: null,
        BillReceipt: null,
      },
      SubmitBillOrder: {
        userName: null,
        userId: null,
        userPhone: null,
        autoPlateNum: null,
        billType: null,
        billDescribe: null,
        billTotal: null,
        billReceipt: null,
        billSubmitTime: null,
        billProgress: null,
      },
      BillOrderRules: {
        InputUserName: [{ required: true, message: '请输入姓名', trigger: 'blur' },],
        InputUserId: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { min: 8, max: 8, message: '工号长度为 8', trigger: 'blur' }
        ],
        InputUserPhone: [
          { required: true, message: '请输入申请人电话', trigger: 'blur' },
          { min: 11, max: 11, message: '电话长度为 11', trigger: 'blur' }
        ],
        SelectAutoPlateNum: [{ required: true, message: '请选择车牌号', trigger: 'change' },],
        SelectBillType: [{ required: true, message: '请选择报账类型', trigger: 'change' },],
        InputBillDescribe: [{ required: true, message: '请输入具体描述', trigger: 'blur' },],
        InputBillTotal: [{ required: true, message: '请输入费用合计', trigger: 'blur' },],
        BillReceipt: { required: true, message: '请上传文件', trigger: 'change' },
      },
    }
  },

  methods: {
    UpdateCurrentTime() {
      const currentDateTime = new Date();
      const dateOptions = { year: 'numeric', month: '2-digit', day: '2-digit' };
      const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit' };
      const formattedDate = currentDateTime.toLocaleDateString(undefined, dateOptions);
      const formattedTime = currentDateTime.toLocaleTimeString(undefined, timeOptions);
      this.SubmitBillOrder.billSubmitTime = `${formattedDate} ${formattedTime}`;
    },
    CreateBill(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('此操作将提交此报账, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.UpdateCurrentTime();
            this.SubmitBillOrder.userName = this.BillOrder.InputUserName;
            this.SubmitBillOrder.billDescribe = this.BillOrder.InputBillDescribe;
            this.SubmitBillOrder.billReceipt = this.BillOrder.BillReceipt;
            this.SubmitBillOrder.billTotal = this.BillOrder.InputBillTotal;
            this.SubmitBillOrder.billType = this.BillOrder.SelectBillType;
            this.SubmitBillOrder.userId = this.BillOrder.InputUserId;
            this.SubmitBillOrder.autoPlateNum = this.BillOrder.SelectAutoPlateNum;
            this.SubmitBillOrder.userPhone = this.BillOrder.InputUserPhone;
            this.SubmitBillOrder.billProgress = 1;
            createBill(this.SubmitBillOrder).then(res => {
              if (res.data.code === '0') {
                this.$message({
                  message: "提交成功",
                  duration: 2000,
                  showClose: true,
                  type: 'success'
                });
                this.goBackPage()
              }
              else {
                this.$message.error('提交失败');
              }
            }).catch((err) => {
              console.log(err)
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }
        else {
          return false;
        }
      })
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}?`)
    },
    GetAutoPlateNum() {
      fetchPlateNums().then(res => {
        const temp = res.data.data;
        const result = [];
        temp.forEach(element => { result.push(Object.values(element)) });
        result.forEach(element => { this.BillOrder.SelectAutoPlateNumOptions.push(element[1]) });
      }).catch((err) => {
        console.log(err);
      })
    },
    BillReceiptGetUrl(response) {
      this.BillOrder.BillReceipt = response;
    },
    goBackPage() {
      this.$router.go(-1)
    },
    InitData() {
      return new Promise((resolve, reject) => {
        try {
          getUserInfoById(localStorage.getItem("userId")).then(res => {
            const data = res.data.data;
            this.BillOrder.InputUserName = data[0].userName;
            this.BillOrder.InputUserId = data[0].userId;
            this.BillOrder.InputUserPhone = data[0].userPhone;
          })
          resolve(); // 表示异步操作成功
        } catch (error) {
          console.log(error);
          reject(error); // 处理异步错误
        }
      });
    },
  },

  created() {
    this.GetAutoPlateNum();
    this.InitData();
  },
}
</script>
  
<style scoped>
.container {
  /* height: 100%; */
  width: 95%;
  margin: 0 auto;
  margin-top: 1%;
  background-color: #ffffff;
}

.apply-container {
  width: 90%;
  height: 100%;
  margin: 0 auto;
  /* background-color: #f2f2f2; */

}

.apply-container-head {
  width: 95%;
  height: 30px;
  margin: 0 auto;
}

.apply-container-body {
  width: 95%;
  height: 92%;
  margin: 0 auto;
  background-color: #ffffff;

}

.apply-container-body-title {
  width: 98%;
  height: 5%;
  margin: 0 auto;
  display: flex;
}

.apply-container-body-title-return {
  width: 100%;
  padding-top: 5px;
  display: flex;
  justify-content: flex-end;
}

.apply-container-body-title-line {
  height: 1px;
  width: 98%;
  margin: 5px auto;
}

.apply-container-body-title-font {
  width: 100%;
  height: 99%;
  font-size: 18px;
  font-weight: bold;
  text-align: left;
  padding-top: 10px;
}

.apply-container-body-content {
  width: 85%;
  height: 100%;
  margin: 20px auto;
  display: flex;

}

.apply-container-body-content-submit {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.apply-container-footer {
  width: 95%;
  height: 10px;
  margin: 0 auto;
}
</style>